package com.hqyj.controller;

import com.github.pagehelper.PageInfo;
import com.hqyj.pojo.User;
import com.hqyj.serviceInf.UserServiceInf;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;


@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserServiceInf userServiceInf;

    //    根据传入用户名信息动态查询所有用户或者单个用户,加分页实现
    @RequestMapping("/getUser")
    @ResponseBody
    public Map<String, Object> getUser(@RequestParam(defaultValue = "1", required = false) int pageNum,
                                       @RequestParam(defaultValue = "5", required = false) int pageSum,
                                       @RequestParam(value = "username", required = false) String username) {
        return userServiceInf.selectUser(pageNum, pageSum, username);
    }

    //    根据字符串模糊查询
    @RequestMapping("/getUserLike")
    @ResponseBody
    public Map<String, Object> getUserLike(@RequestParam(defaultValue = "1", required = false) int pageNum,
                                           @RequestParam(defaultValue = "6", required = false) int pageSum,
                                           @RequestParam(value = "username", required = false) String username) {
//        System.out.println(username);
        return userServiceInf.selectUserLike(pageNum, pageSum, username);
    }

    //    用户注册
    @RequestMapping("/userEnroll")
    @ResponseBody
    public Map<String, Object> userEnroll(@RequestBody User user) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("code", -1);
        map.put("message", "注册失败");
        if (userServiceInf.insertUser(user) > 0) {
            map.put("code", 200);
            map.put("message", "注册成功");
            map.put("url", "/sys/goLogin");
        }
        return map;
    }

    //    注册时检查用户名是否重复
    @RequestMapping("/enrollCheck")
    @ResponseBody
    public Map<String, Object> enrollCheck(@RequestParam String username) {
//        System.out.println(username);
        Map<String, Object> map = userServiceInf.selectUser(1, 1, username);
        if (((PageInfo<User>) map.get("userPageInfo")).getList().size() == 0) {
            map.put("message", "ok");
        } else {
            map.put("code", -2);
            map.put("message", "该用户名已被使用");
        }
        return map;
    }

    //    管理员添加用户
    @RequestMapping(value = "/addUser", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> addUser(@RequestBody User user) {
//        System.out.println(user);
        HashMap<String, Object> map = new HashMap<>();
        map.put("code", -1);
        map.put("message", "添加失败");
        if (userServiceInf.insertUser(user) > 0) {
            map.put("code", 200);
            map.put("message", "添加成功");
            map.put("url", "/user/getUser");
        }
        return map;
    }

    //    修改用户时对用户的信息查询
    @RequestMapping("/showUser")
    public String showUser(String username, Model model) {
        Map<String, Object> map = userServiceInf.selectUser(1, 1, username);
        User user = new User();
        PageInfo<User> upi = (PageInfo<User>) map.get("userPageInfo");
        if (upi.getList().size() > 0) {
            user = upi.getList().get(0);
            model.addAttribute("user", user);
            return "user-edit";
        }
        return "redirect:getUser";
    }

    //    修改用户
    @RequestMapping("/editUser")
    @ResponseBody
    public Map<String, Object> editUser(@RequestBody User user) {
//        System.out.println(user);
        HashMap<String, Object> map = new HashMap<>();
        map.put("code", -1);
        map.put("message", "修改失败");
        if (userServiceInf.updateUser(user) > 0) {
            map.put("code", 200);
            map.put("message", "修改成功");
            map.put("url", "/user/getUser");
        }
        return map;
    }

    //    删除用户
    @RequestMapping("/removeUser")
    public String removeUser(int id, Model model) {
        if (userServiceInf.deleteUser(id) > 0) {
            model.addAttribute("message", "删除成功");
        } else {
            model.addAttribute("message", "删除失败");
        }
        return "redirect:getUser";
    }

    //登录
    @RequestMapping("/login")
    @ResponseBody
    public Map<String, Object> login(String username, String password) {
        return userServiceInf.selectUserByUserName(username, password);
    }

//    用户登出
    @RequestMapping("/logOut")
    public String logOut() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "login";
    }

    //用户个人信息查找
    @RequestMapping("/showSelf")
    public ModelAndView showSelf(String username, ModelAndView modelAndView){
        Map<String, Object> map = userServiceInf.selectUser(1, 1, username);
        User user = new User();
        PageInfo<User> upi = (PageInfo<User>) map.get("userPageInfo");
        if (upi.getList().size() > 0) {
            user = upi.getList().get(0);
            modelAndView.addObject("user", user);
            modelAndView.setViewName("self");
        }
        return modelAndView;
    }

    //    头像上传
    @RequestMapping("/upload")
    @ResponseBody
    public Map<String, Object> uploadFile(MultipartFile file, String username,
                             String password, String phone,
                             String email, String birthday) throws ParseException {
//        新建user对象接收数据，用于修改
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setPhone(phone);
        user.setEmail(email);
//        将时间字符串转换成date格式
        user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
        //得到当前的classpath的绝对路径的uri表示
        String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
        String path = rootPath.substring(1, rootPath.indexOf("target")) + "src/main/webapp/static/users/";
//        System.out.println(username);
//        以路径区分每个用户的头像文件夹，dbpath是存数据库的路径
        String dbpath = username + "/headImage/";
        path += dbpath;
//        System.out.println(path);
        //文件名
        String filename = file.getOriginalFilename();
//        System.out.println(filename);
        dbpath += filename;
//        将路径存入user对象
        user.setHeadimg(dbpath);
        //创建新文件
        File newFile = new File(path, filename);
        //判断目标文件所在目录是否存在
        if(!newFile.getParentFile().exists()){
            //不存在 创建
            newFile.getParentFile().mkdirs();
        }
        //将内存中的数据写入磁盘
        try {
            file.transferTo(newFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
//        上传图片路径到数据库
        int i = userServiceInf.updateUser(user);
        HashMap<String, Object> map = new HashMap<>();
        map.put("code", i);
        if(i > 0){
            map.put("message", "修改成功");
        }else{
            map.put("message", "修改失败");
        }
        return map;
    }

    //    头像下载（未使用）
    @RequestMapping("/down")
    public String downFile(HttpServletResponse response, String headimg) throws IOException {
        String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
        String path = rootPath.substring(1, rootPath.indexOf("target")) + "src/main/webapp/static/users/";
        path += headimg.substring(0, headimg.lastIndexOf("/") + 1);
//        // 下载文件的名字，假设为banner_1.jpg
        String fileName = headimg.substring(headimg.lastIndexOf("/") + 1);
        System.out.println(path);
        StringBuilder s = new StringBuilder();
        //获取输入流
        InputStream is = new BufferedInputStream(new FileInputStream(new File(path,fileName)));
        //转码，免得文件名中文乱码
        String filename = URLEncoder.encode(fileName,"UTF-8");
        //设置文件下载头
        response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
        //1.设置文件ContentType类型，这样设置，会自动判断下载文件类型
        response.setContentType("multipart/form-data");
        BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
        int len = 0;
        while((len = is.read()) != -1){
            out.write(len);
            out.flush();
        }
        out.close();
        return "success";
    }
}
